<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NSpace align="center">
          考核名称:
          <NInput style="width: 200rem" placeholder="请输入考核名称" v-model:value="paginationReactive.appraiseName" clearable />
          <NButton type="primary" style="width: 78rem" ghost
            @click="() => ((paginationReactive.page = 1), getAssessList())">
            查询
          </NButton>
        </NSpace>
        <NButton type="primary" style="width: 115rem" @click="$router.push({ path: '/OA/Assess/AssessAdd' })">
          新建考核
        </NButton>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :columns="columns" :data="tableData" :pagination="false"
        :loading="tableLoading" />
    </template>

    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal :auto-focus="false" v-model:show="modalVisible" @close="modalVisible = false">
    <VDialogContent @close="modalVisible = false" @submit="assessTitle ? recall() : assessDelete()"
      :title="assessTitle ? '撤回提示' : '删除提示'">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        {{ assessTitle ? '您确定撤回该条考核吗？' : '您确定删除该条考核吗？' }}
      </div>
    </VDialogContent>
  </NModal>
</template>
<script setup lang="ts">
import { NSpace, NButton, NDataTable, NPagination, useMessage, NModal, NInput } from 'naive-ui'
import { h, reactive, ref, watch, onDeactivated } from 'vue'
import { sendRequest } from '@/utils/api'
import { useRoute } from 'vue-router'
import type { DataTableColumns } from 'naive-ui'
import TableView from '@/components/TableView.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import router from '@/router'
import { useViewerStore } from '@/views/OA/Common/store'
import { RecordType } from '@/router/utils'

const useStore = useViewerStore()
const message = useMessage()
const route = useRoute()
const modalVisible = ref(false)

const columns: DataTableColumns = [
  {
    title: '发起人',
    key: 'userName',
    width: 60,
    align: useStore.isCenter
  },
  {
    title: '考核名称',
    key: 'appraiseName',
    width: 60,
    align: useStore.isCenter
  },
  {
    title: '被考核人数',
    key: 'appraiseNum',
    width: 60,
    align: useStore.isCenter
  },
  {
    title: '参与投票人数',
    key: 'voteNum',
    width: 60,
    align: useStore.isCenter
  },
  {
    title: '发起日期',
    key: 'submitTime',
    width: 100,
    align: useStore.isCenter
  },
  {
    title: '开始时间',
    key: 'startTime',
    width: 100,
    align: useStore.isCenter
  },
  {
    title: '结束时间',
    key: 'endTime',
    width: 100,
    align: useStore.isCenter
  },
  {
    title: '状态',
    key: 'fromStatus',
    width: 60,
    align: useStore.isCenter
  },
  {
    title: '操作',
    key: 'action',
    align: useStore.isCenter,
    width: 120,
    fixed: 'right',
    render: (row: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            RecordType.setRouteNameTypeFalse('A0558')
            router.push({ path: '/OA/Assess/AssessInfo', query: { id: row.id } })
          }
        },
        {
          default: () => '详情'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          style: { display: row.fromStatus == '审批中' ? 'inlne-block' : 'none' },
          onClick: async () => {
            assessId.value = row.id
            assessTitle.value = true
            modalVisible.value = true
          }
        },
        {
          default: () => '撤回'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          style: { display: row.fromStatus == '已完成' ? 'inlne-block' : 'none' },
          onClick: async () => exportAssess(row)
        },
        {
          default: () => '导出'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          color: useStore.color.delete,
          quaternary: true,
          style: { display: row.fromStatus != '审批中' ? 'inlne-block' : 'none' },
          onClick: async () => {
            assessId.value = row.id
            assessTitle.value = false
            modalVisible.value = true
          }
        },
        {
          default: () => '删除'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          style: { display: row.fromStatus != '审批中' ? 'inlne-block' : 'none' },
          onClick: async () => router.push({ path: '/OA/Assess/AssessInfoList', query: { appraiseId: row.id } })
        },
        {
          default: () => '问卷列表'
        }
      )
      // h(
      //   NButton,
      //   {
      //     type: 'primary',
      //     quaternary: true,
      //     onClick: () => {
      //       router.push({
      //         path: '/OA/Assess/AssessUpdate',
      //         query: { id: row.id, flat: true as never }
      //       })
      //     }
      //   },
      //   {
      //     default: () => '再次发起'
      //   }
      // )
    ]
  }
]
// 上一页下一页
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  appraiseName: null, //考核名称
  onChange: (page: number) => {
    paginationReactive.page = page
    getAssessList()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    getAssessList()
  }
})
// 撤回
const assessTitle: any = ref(null)
const assessId = ref()
const recall = async () => {
  modalVisible.value = false
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'receiveOrDispatch',
    api: 'dispatchRevoke',
    override: {
      data: {
        functionCode: 'A0558',
        resourceId: assessId.value
      }
    }
  })
  if (error) return message.error('撤回失败'), (tableLoading.value = false)
  if (res.code !== 0) return message.error('撤回失败'), (tableLoading.value = false)
  getAssessList()
  message.success('撤回成功')
}
// 删除
const assessDelete = async () => {
  modalVisible.value = false
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'assess',
    api: 'assessDelete',
    override: {
      data: [assessId.value]
    }
  })
  if (error) return message.error('删除失败'), (tableLoading.value = false)
  if (res.code !== 0) return message.error('删除失败'), (tableLoading.value = false)
  getAssessList()
  message.success('删除成功')
}
// 导出
const exportAssess = async (row: any) => {
  tableLoading.value = true
  const [error, res, headers] = await sendRequest({
    module: 'assess',
    api: 'assessExport',
    override: {
      params: {
        id: row.id
      }
    }
  })
  if (error) return message.error('导出失败'), (tableLoading.value = false)
  download(headers, res, '考核')
  message.success('导出成功')
  tableLoading.value = false
}
// 下载
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '.xlsx'
  if (!filename.includes('xlsx')) filename = filename.replace('xls', 'xlsx')
  const a = document.createElement('a')
  a.href = window.URL.createObjectURL(new Blob([data]))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}
// 获取列表
const tableData = ref([])
const tableLoading = ref(false)
const getAssessList = async () => {
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'assess',
    api: 'assessList',
    override: {
      params: {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        appraiseName: paginationReactive.appraiseName
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  tableData.value = []
  setTimeout(() => {
    tableData.value = res.data.list
    paginationReactive.itemCount = res.data.totalCount
  }, 0)
}

const keyUpDown = (e: any) => e.key == 'Enter' && getAssessList()
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route,
  async () => {
    if (route.path == '/OA/Assess/AssessList') {
      getAssessList()
      window.addEventListener('keyup', keyUpDown, false)  // 回车
    }
  },
  { deep: true, immediate: true }
)

</script>
<style scoped lang="scss">
.table {
  padding: 29rem 30rem 42rem;
}
</style>
  